<template name="postComment">
	<view class="postComment">
		<view class="perFilesContainer" v-if="wiatUpFileArry.length != 0">
			<view class="perFiles">
				<view class="item" v-for="(item, index) in wiatUpFileArry" :key="index">
					<image lazy-load @click="perViewFile(index)" :src="item.file_type === 0 ? item.file_path : item.previewImage" mode="aspectFill"></image>
					<text @click="removeFile(index)" class="iconfont icon-guanbi file_claer"></text>
					<text @click="perViewFile(index)" v-if="item.file_type === 1" class="iconfont icon-b- video-bofang"></text>
					<text v-if="item.file_type === 1" class="video_preview_info">{{ secondToDate(item.duration) }}</text>
					<text class="show_index">{{ index + 1 }}</text>
				</view>
			</view>
		</view>

		<view class="inputModel">
			<input class="commentContent" type="text" v-model="commentContent" />
			<text class="iconfont icon-jia1" @click="selectFile"></text>
			<text class="sub_btn" @click="postAndUpload">发送</text>
		</view>
	</view>
</template>

<script>
import {config} from '../../utils/request/config.js';
let qiniu = require('../../utils/qiniuyun/qiniuUploader');
let sparkmd5 = require('../../utils/SparkMD5');
const FILE_TYPE = {
	image: 0,
	video: 1,
	audio: 2
};
const FILE_MAX_SIEZ = {
	image: 1024 * 1024 * 4,
	video: 1024 * 1024 * 8,
	audio: 1024 * 1024 * 4
};
export default {
	name: 'postComment',
	props: ['aid'],
	data() {
		return {
			commentContent: '',
			wiatUpFileArry: []
		};
	},
	methods: {
		removeFile(index) {
			this.wiatUpFileArry.splice(index, 1);
		},
		perViewFile(toindex) {
			uni.navigateTo({
				url: '../utils/previewImageAndVideo?index=' + toindex,
				success: res => {
					console.log(toindex);
					uni.setStorageSync('previewFileArry', this.wiatUpFileArry);
					uni.setStorageSync('previewFileindex', toindex);
					getApp().globalData.previewFileArry = this.wiatUpFileArry;
				}
			});
		},
		secondToDate(second) {
			let h = Math.floor(second / 3600) * 60;
			let m = Math.floor((second / 60) % 60) + h;
			let s = Math.floor(second % 60);
			return m + h + ':' + s;
		},
		selectFile() {
			uni.showActionSheet({
				itemList: ['选择图片', '选择视频'],
				success: res => {
					switch (res.tapIndex) {
						case 0:
							this.selectImage();
							break;
						case 1:
							this.selectVideos();
							break;
						default:
							break;
					}
				}
			});
		},
		selectImage() {
			if (this.wiatUpFileArry.length < 9) {
				uni.chooseImage({
					count: 9 - this.wiatUpFileArry.length, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: res => {
						console.log(res);
						res.tempFiles.forEach((item, index) => {
							if (item.size <= FILE_MAX_SIEZ.image) {
								// 获取图片原始信息
								uni.getImageInfo({
									src: item.path,
									success: imgInfoRes => {
										this.wiatUpFileArry.push({
											file_path: imgInfoRes.path,
											file_type: FILE_TYPE.image,
											type_name: imgInfoRes.type,
											file_width: imgInfoRes.width,
											file_height: imgInfoRes.height,
											file_ratio: imgInfoRes.width / imgInfoRes.height,
											size: item.size
										});
									}
								});
							} else {
								uni.showToast({
									title: '第' + index + '个图片超过4MB',
									icon: 'none'
								});
							}
						});
					}
				});
			} else {
				uni.showToast({
					title: '最多选择9个文件哦!',
					icon: 'none'
				});
			}
		},
		selectVideos() {
			if (this.wiatUpFileArry.length < 9) {
				uni.chooseVideo({
					count: 9 - this.wiatUpFileArry.length,
					maxDuration: 60,
					sourceType: ['camera', 'album'],
					success: res => {
						console.log(res);
						if (res.size <= FILE_MAX_SIEZ.video) {
							this.wiatUpFileArry.push({
								file_path: res.tempFilePath,
								file_type: FILE_TYPE.video,
								previewImage: res.thumbTempFilePath,
								duration: res.duration,
								file_width: res.width,
								file_height: res.height,
								file_ratio: res.width / res.height,
								size: res.size
							});
						} else {
							uni.showToast({
								title: '当前视频超过8MB',
								icon: 'none'
							});
						}
					}
				});
			} else {
				uni.showToast({
					title: '最多选择9个文件哦!',
					icon: 'none'
				});
			}
		},
		postAndUpload() {
			// 判断是否符合条件
			let postInfoArrys = {
				content: this.commentContent,
				files: [],
				aid: this.aid
			};
			if (this.commentContent.length < 2 || this.commentContent.length > 100) {
				uni.showToast({
					title: '2~100字符哦!',
					icon: 'none'
				});
				return;
			}

			// 验证完毕 弹出上传提示
			uni.showLoading({
				title: '上传中...',
				mask: true
			});

			// 判断是否有图片 没有图片就上传文字内容
			if (this.wiatUpFileArry.length === 0) {
				this.postArticle(postInfoArrys);
				return;
			}

			/* 循环上传文件！调用七牛返回值样例
					hash: "Ft0M_39uI7XXu1jR8yOvTZoyoy2-"
					imageUrl: "http://q0zr7m3w7.bkt.clouddn.com/9193c718845d4b0e83deed1875d8a925"
					key: "9193c718845d4b0e83deed1875d8a925"
				*/
			let upIndex = 0;
			this.wiatUpFileArry.forEach((item, index) => {
				qiniu.upload(
					item.file_path,
					upload_res => {
						upIndex++;
						if (item.file_type === 0) {
							// 图片上传
							postInfoArrys.files.push({
								file_qiniu_hash: upload_res.hash, // 七牛Hash
								file_path: upload_res.imageUrl, // 文件的网络路径
								file_key: upload_res.key, // 文件的MD5值
								file_type: FILE_TYPE.image, // 文件类型
								file_width: item.file_width,
								file_height: item.file_height,
								file_ratio: item.file_ratio,
								file_preview: '', // 缩略图
								file_type_details: this.getFileTypeDetails(item.file_path) // 文件的类型名 png...
							});
						} else if (item.file_type === 1) {
							// 视频上传
							postInfoArrys.files.push({
								file_qiniu_hash: upload_res.hash, // 七牛Hash
								file_path: upload_res.imageUrl, // 文件的网络路径
								file_key: upload_res.key, // 文件的MD5值
								file_type: FILE_TYPE.video, // 文件类型
								file_width: item.file_width,
								file_height: item.file_height,
								file_ratio: item.file_ratio,
								file_preview: upload_res.imageUrl + '?vframe/jpg/offset/1', // 缩略图
								file_type_details: this.getFileTypeDetails(item.file_path) // 文件的类型名 mp4...
							});
						}
						if (upIndex === this.wiatUpFileArry.length) {
							this.postArticle(postInfoArrys);
						} else {
							uni.showLoading({
								title: '上传进度：' + upIndex + '/' + this.wiatUpFileArry.length,
								mask: true
							});
						}
					},
					error => {
						uni.hideLoading();
						uni.showToast({
							title: '发生错误，请重试',
							icon: 'none'
						});
					},
					{
						region: 'SCN',
						uploadURL: 'https://up-z2.qiniup.com',
						domain: 'https://file.ndmrak.com/',
						key: this.make_md5(item.file_path),
						uptokenURL: config.baseURL + '/api/filemanage/upload/'
					}
				);
			});
		},
		make_md5(file) {
			let fileObj = uni.getFileSystemManager().readFileSync(file);
			let spark = new sparkmd5.ArrayBuffer();
			spark.append(fileObj);
			let hexHash = spark.end(false);
			return hexHash;
		},
		getFileTypeDetails(fileName) {
			let nameSplit = fileName.split('.');
			let name = nameSplit[nameSplit.length - 1];
			return name;
		},
		postArticle(postInfoArrys) {
			this.$http
				.request({
					url: '/api/article/comment/',
					data: postInfoArrys,
					method: 'post'
				})
				.then(res => {
					uni.hideLoading();
					if (res.statusCode == 201) {
						console.log('发布成功:', res.data);
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						// 清理资源
						this.commentContent = '';
						this.wiatUpFileArry = [];
						// 成功回调
						this.$emit('inputPostCallback',res.data)
					} else {
						console.log('发布失败:', res);
						uni.showToast({
							title: '发布失败:' + res,
							icon: 'none'
						});
					}
				})
				.catch(error => {
					uni.hideLoading();
					uni.showToast({
						title: '发生错误：' + error,
						icon: 'none'
					});
					console.log('发生错误：', error);
				});
		}
	}
};
</script>

<style lang="scss">
.postComment {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 750rpx; // 750rpx 恒等于 100%
	// min-height: 75rpx;
	z-index: 9999;
	flex-wrap: wrap;
	// justify-content: center;
	// align-items: center;
}

.inputModel {
	width: 100%;
	height: 90rpx;
	align-items: center;
	background-color: white;
}

.commentContent {
	width: 60%;
	height: 60rpx;
	background-color: #f5f5f5;
	margin: 0 10rpx;
	border-radius: 30rpx;
	padding: 0 30rpx;
}

.perFilesContainer {
	width: 100%;
	justify-content: flex-end;
}

.perFiles {
	height: 210rpx;
	max-width: 100%;
	overflow-x: auto;
	flex-shrink: 0;
	flex-flow: row;
	background-color: rgbs(0, 0, 0, 0.5);
}

.item {
	position: relative;
	flex-shrink: 0;
	width: 200rpx;
	height: 200rpx;
	padding: 5rpx;

	.file_claer {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		color: red;
	}

	.video-bofang {
		position: absolute;
		top: 45rpx;
		right: 65rpx;
		font-size: 80rpx;
		color: white;
	}

	.video_preview_info {
		display: inline-block;
		position: absolute;
		width: 150rpx;
		top: 125rpx;
		right: 30rpx;
		font-size: 30rpx;
		text-align: center;
		color: white;
	}

	.show_index {
		position: absolute;
		bottom: 10rpx;
		left: 10rpx;
		font-size: 25rpx;
		padding: 5rpx 15rpx;
		color: white;
		border-radius: 30rpx;
		background: rgba(0, 0, 0, 0.6);
	}
}

.icon-jia1 {
	font-size: 60rpx;
}

.sub_btn {
	position: absolute;
	right: 20rpx;
	bottom: 15rpx;
	background-color: #139eff;
	color: #fdfefd;
	text-align: center;
	border-radius: 60rpx;
	line-height: 55rpx;
	font-size: 32rpx;
	letter-spacing: 7rpx;
	height: 60rpx;
	width: 120rpx;
}

image {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
}
</style>
